import type { PaginationProps } from "@pureadmin/table";
import { getDataBySQLDesc } from "@/api/common";
import { type Ref, reactive, ref, onMounted, h } from "vue";
import type { PlusColumn } from "plus-pro-components";
import { ElSelect, ElOption, ElPagination } from "element-plus";
import moment from "moment";

export function usePurchasePriceData() {
  const form = ref({
    wlbh: "",
    sxsj_begin: "",
    sxsj_end: "",
    hjdjd: "'HPYM'",
    hjddjb: "'HJ1','HJ2'",
    hjdzt: "'Y'"
  });
  // 料件编码选项数据
  const ljbhOptions = ref<{ label: string; value: string }[]>([]);

  const dataList = ref([]);
  const chartOption = ref({
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: []
    },
    yAxis: {
      type: "value"
    },
    series: [
      {
        data: [],
        type: "line",
        smooth: true
      }
    ]
  });
  const isShow = ref(false);
  const loading = ref(true);

  // 物料编号分页相关状态
  const ljbhLoading = ref(false);
  const ljbhPagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
  });

  // 存储搜索关键词
  const ljbhKeyword = ref("");

  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });

  // 加载料件编号数据
  const loadLjbhData = async (query = "", reset = false) => {
    if (ljbhLoading.value) return;

    if (reset) {
      ljbhPagination.currentPage = 1;
    }

    ljbhLoading.value = true;
    try {
      const { data, total } = await getDataBySQLDesc({
        action: "public/get_wlxx",
        jhpm: query,
        pageindex: ljbhPagination.currentPage.toString(),
        pagesize: ljbhPagination.pageSize.toString()
      });

      if (data?.length) {
        const newOptions = data.map(item => ({
          label: item["品名"],
          value: item["料件编号"]
        }));

        ljbhOptions.value = newOptions;
        ljbhPagination.total = total || 0;
      } else {
        ljbhOptions.value = [];
        ljbhPagination.total = 0;
      }
    } catch (error) {
      console.error("料件编号加载失败:", error);
      ljbhOptions.value = [];
      ljbhPagination.total = 0;
    } finally {
      ljbhLoading.value = false;
    }
  };

  // 料件编号搜索方法
  const searchOutsource1 = async (query = "") => {
    ljbhKeyword.value = query;
    await loadLjbhData(query, true);
  };

  // 分页改变处理方法
  const handleLjbhPageChange = (page: number) => {
    ljbhPagination.currentPage = page;
    loadLjbhData(ljbhKeyword.value, false);
  };

  const columns: TableColumnList = [
    {
      label: "生效日期",
      prop: "生效日期",
      minWidth: 160
    },
    {
      label: "失效日期",
      prop: "失效日期",
      minWidth: 160
    },
    {
      label: "供应商",
      prop: "供应商"
    },
    {
      label: "委外",
      prop: "委外"
    },
    {
      label: "币种",
      prop: "币种"
    },
    {
      label: "含税",
      prop: "含税"
    },
    {
      label: "核决内容",
      prop: "核决内容",
      minWidth: 160
    },
    {
      label: "上次单价",
      prop: "上次单价",
      minWidth: 160
    },
    {
      label: "单价",
      prop: "单价",
      minWidth: 160
    },
    {
      label: "核价单价",
      prop: "核价单价",
      minWidth: 160
    }
  ];

  const search_columns: PlusColumn[] = [
    {
      label: "料件编号",
      prop: "wlbh",
      valueType: "select",
      fieldProps: {
        filterable: true,
        remote: true,
        placeholder: "请选择料件编号",
        loading: ljbhLoading.value
      },
      renderField(value, onChange) {
        return h("div", { class: "pagination-select-container" }, [
          h(
            ElSelect as any,
            {
              modelValue: value,
              "onUpdate:modelValue": (val: any) => {
                form.value.wlbh = val;
                onChange && onChange(val);
              },
              filterable: true,
              remote: true,
              loading: ljbhLoading.value,
              placeholder: "请选择料件编号",
              onVisibleChange: (visible: boolean) => {
                if (visible && ljbhOptions.value.length === 0) {
                  searchOutsource1("");
                }
              },
              onRemoteQuery: (query: string) => {
                ljbhKeyword.value = query;
                ljbhPagination.currentPage = 1;
                searchOutsource1(query);
              }
            },
            {
              default: () =>
                ljbhOptions.value.map(item =>
                  h(ElOption as any, {
                    key: item.value,
                    label: item.label,
                    value: item.value
                  })
                ),
              footer: () =>
                h(ElPagination, {
                  small: true,
                  layout: "prev, pager, next",
                  pageSize: ljbhPagination.pageSize,
                  currentPage: ljbhPagination.currentPage,
                  total: ljbhPagination.total,
                  onCurrentChange: handleLjbhPageChange,
                  class: "pagination-footer"
                })
            }
          )
        ]);
      }
    },
    {
      label: "生效开始时间",
      prop: "sxsj_begin",
      valueType: "date-picker",
      fieldProps: {
        placeholder: "请选择订单开始时间",
        format: "YYYY-MM-DD",
        valueFormat: "YYYY-MM-DD",
        type: "date",
        clearable: true,
        editable: false,
        prefixIcon: "el-icon-date",
        disabledDate: date => date && date > Date.now()
      }
    },
    {
      label: "订单结束时间",
      prop: "sxsj_end",
      valueType: "date-picker",
      fieldProps: {
        placeholder: "请选择订单结束时间",
        format: "YYYY-MM-DD",
        valueFormat: "YYYY-MM-DD",
        type: "date",
        clearable: true,
        editable: false,
        prefixIcon: "el-icon-date",
        disabledDate: date => date && date > Date.now()
      }
    }
  ];

  const handleChange = (values: any) => {
    console.log(values, "change");
  };

  const handleSearch = async (values: any) => {
    await onSearch();
  };

  const handleReset = () => {
    form.value.sxsj_begin = "";
    form.value.sxsj_end = "";
    form.value.wlbh = "";
    onSearch();
  };

  function handleSizeChange(val: number) {
    pagination.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    pagination.currentPage = val;
    onSearch();
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  const fetchParams = async (
    hsmc: string
  ): Promise<Record<string, string[]>> => {
    const params = { action: "public/get_bi_sjfw", hsmc };
    const { data } = await getDataBySQLDesc(params);

    return data.reduce((acc, item) => {
      acc[item["参数编码"]] = item["参数值"];
      return acc;
    }, {});
  };
  const fetchTime = async (): Promise<string> => {
    const params = { action: "public/get_server_sysdate" };
    const { data } = await getDataBySQLDesc(params);
    return data[0];
  };
  async function onSearch() {
    loading.value = true;
    try {
      // 创建一个新的表单对象，包含拼接了时间的日期
      const formData = {
        ...form.value,
        sxsj_begin: form.value.sxsj_begin
          ? `${form.value.sxsj_begin} 00:00:00`
          : "",
        sxsj_end: form.value.sxsj_end ? `${form.value.sxsj_end} 23:59:59` : ""
      };
      const params = await fetchParams("get_yf_cgjg_qsfx");
      const { data } = await getDataBySQLDesc({
        action: "biz/reports/get_yf_cgjg_qsfx",
        ...params,
        ...formData
      });
      console.log(data, "data");
      dataList.value = data;
      chartOption.value.xAxis.data = data.map(item => item["生效日期"]);
      chartOption.value.series[0].data = data.map(item => item["单价"]);
      setTimeout(() => {
        loading.value = false;
      }, 500);
    } catch (error) {
      loading.value = false;
    }
  }

  onMounted(async () => {
    // await searchOutsource1("");
    await fetchTime().then(res => {
      form.value.sxsj_begin = moment(res["本年度开始时间"]).format(
        "YYYY-MM-DD"
      );
      form.value.sxsj_end = res["日期"];
    });
    onSearch();
  });

  return {
    form,
    isShow,
    loading,
    columns,
    dataList,
    chartOption,
    pagination,
    onSearch,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    search_columns,
    handleChange,
    handleSearch,
    handleReset
  };
}
